var assert = require('../assert');

exports.wxLogin = function (req, res, next) {
    var redirectUrl = req.query.redirect;
    var stateDict = {};
    stateDict.host = 'koudai.lovepinyao.com';
    stateDict.path = '/login/wxLoginJump';
    stateDict.params = {redirect: redirectUrl};
    stateDict.from = 'koudai';
    stateDict.operation = 'login';
    stateDict.env = 'normal';
    var stateStr = new assert.base64Assert().encode(JSON.stringify(stateDict));
    //构造微信跳转链接
    console.log(stateStr);
    res.redirect(assert.WEIXIN_LOGIN + '?params=' + stateStr);
};

exports.wxLoginJump = function (req, res, next) {

    var params = req.query.params;
    var loginErr = req.query.loginErr;
    if (!params || loginErr) {
        res.render('error', {message: loginErr});
        return;
    }
    //若返回正常,则进行逻辑处理
    var paramsObj = JSON.parse(new assert.base64Assert().decode(params));
    var userId = paramsObj.userId;
    var openId = paramsObj.openId;
    var unionId = paramsObj.unionId;
    var redirectObj = paramsObj.paramsRedirect;
    //写入userId到session,写入openId到session
    req.session.userId = userId;
    req.session.userKDOpenId = openId;
    res.cookie('userToken', new assert.base64Assert().encode(userId), {expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)});
    //重新跳转回原页面
    res.redirect(redirectObj.params.redirect);
};

exports.login = function (req, res) {
    var JADE_VAR = assert.getJADEVAR();
    var redirectUrl = req.query.redirect;
    //分两种情况,微信内,微信自动登陆,微信外,跳转登陆页面
    if (!req.query.wxBan) {
        var UserAgent = req.headers['user-agent'];
        var isWx = false;
        if (UserAgent.indexOf('MicroMessenger') != -1) {
            isWx = true;
        }
        if (isWx) {
            res.redirect('/login/wxLogin?redirect='+redirectUrl);
            return;
        }
    }
    res.render('login/login', JADE_VAR);
};

exports.doLogin = function (req, res) {
    //接收参数获取用户填写信息,请求注册或登陆接口
    var mobile = req.body.mobile;
    var codeAjax = req.body.code;
    var password = req.body.password;
    var username = req.body.username;

    assert.validateRequest(req.body, function (code, message) {
        if (code == 1) {
            //正确的请求方式
            /**
             * 开始进行数据请求,根据mobile和username的参数值是否为空来确定是何种登陆方式
             */
            if (username) {
                //用户名不为空则默认为账号密码登陆
                if (!password) {
                    res.send({code: 101, message: "密码不能为空"});
                    return;
                }
                //开始请求数据
                assert.apiParseRequest('get', '/parse/login', {
                    username: username,
                    password: password
                }).then(function (results) {
                    if (results.error) {
                        if (results.code == 101) {
                            results.error = '用户名不存在或密码错误';
                        }
                        res.send({code: results.code, message: results.error});
                    } else {
                        req.session.userId = results.objectId;
                        res.send({
                            code: 200,
                            message: "请求成功",
                            data: {userId: results.objectId, redirect: req.session.redirectUrl}
                        });
                    }
                }, function (body, error) {
                    res.send(error);
                })
            } else {
                if (mobile) {
                    if (!code) {
                        res.send({code: 102, message: "验证码不能为空"});
                        return;
                    }
                    //请求数据
                    assert.apiParseRequest('post', '/parse/functions/mobileFastLogin', {
                        mobile: mobile,
                        code: codeAjax
                    }).then(function (results) {
                        if (results.error) {
                            res.send({code: results.code, message: results.error});
                        } else {
                            req.session.userId = results.result.objectId;
                            console.log(req.session.redirectUrl);
                            res.send({
                                code: 200,
                                message: "请求成功",
                                data: {userId: results.result.objectId, redirect: req.session.redirectUrl}
                            });
                        }
                    }, function (body, error) {
                        res.send(error);
                    })
                } else {
                    res.send({code: 103, message: "提交数据错误"});
                }
            }
        } else {
            res.send({code: 400, message: message});
        }
    })
};

exports.withoutLoginCodeSend = function (req, res, next) {
    //通过手机号获取短信验证码
    var mobile = req.body.mobile;
    var timeStr = req.body.timeStr;
    var sign = req.body.sign;
    var action = req.body.action;
    var send_type = req.body.smsType;
    if (!send_type) {
        send_type = 'kd_mobileLogin';
    }

    assert.validateRequest(req.body, function (code, message) {
        if (code == 1) {
            /*进行验证码请求逻辑*/
            var data = {
                mobile: mobile,
                send_type: send_type
            };
            assert.apiParseRequest('post', '/parse/functions/sendSMS', data).then(function (results) {
                if (results.error) {
                    res.send({code: results.code, message: results.error});
                } else {
                    res.send({code: 200, message: "发送成功"});
                }
            }, function (err, error) {
                res.send({code: 101, message: "请求发送失败"});
            })
        } else {
            res.send({code: 400, message: message});
        }
    })
};

exports.register = function (req, res, next) {
    var mobile = req.body.mobile;
    var smsCode = req.body.code;
    var password = req.body.password;
    if (!mobile || !smsCode || !password) {
        res.send({code: 403, message: "非法请求"});
    }
    //先验证请求是否是加密的请求
    assert.validateRequest(req.body, function (code, message) {
        if (code == 1) {
            //验证通过,验证验证码是否正确
            assert.apiParseRequest('post', '/parse/functions/validateSMSCode', {
                sms_code: smsCode,
                code_type: 'kd_sign',
                mobile: mobile
            }).then(function (results) {
                if (results.error) {
                    res.send({code: 101, message: "验证码错误"});
                } else {
                    //验证通过,开始注册
                    assert.apiParseRequest('post', '/parse/users', {
                        username: mobile,
                        password: password,
                        mobile: mobile,
                        signFrom: 'koudai',
                        nickname: mobile.substr(0, 3) + "****" + mobile.substr(-4, 4),
                        userType: 'normal',
                        age: '',
                        birthday: '',
                        deviceType: ''
                    }).then(function (users) {
                        if (users.objectId) {
                            //注册成功
                            req.session.userId = users.objectId;
                            //返回数据
                            res.send({code: 200, userToken: users.objectId, message: "注册成功"});
                            assert.apiParseRequest('post', '/parse/functions/addUserPoints', {
                                userId: users.objectId,
                                addType: 'mobileSign',
                                number: 100
                            }).then(function (results) {
                                console.log(results);
                                console.log("积分添加成功");
                            }, function (err, error) {
                                console.log(err, error);
                            });
                        } else {
                            if (users.code == 202) {
                                res.send({code: 202, message: "该手机号已经注册,请直接登陆"});
                            } else {
                                res.send({code: 404, message: "注册失败:" + users.error});
                            }
                        }
                    }, function (err, error) {
                        res.send({code: 404, message: "网络错误"});
                    })
                }
            }, function (err, error) {
                res.send({code: 404, message: "请求验证失败"});
            })
        } else {
            res.send({code: 404, message: "非法的请求"});
        }
    })
};

exports.resetPassword = function (req, res, next) {
    var mobile = req.body.mobile;
    var smsCode = req.body.code;
    var password = req.body.password;
    if (!mobile || !smsCode || !password) {
        res.send({code: 403, message: "非法请求"});
    }
    //先验证请求是否是加密的请求
    assert.validateRequest(req.body, function (code, message) {
        if (code == 1) {
            //验证通过,验证验证码是否正确
            assert.apiParseRequest('post', '/parse/functions/validateSMSCode', {
                sms_code: smsCode,
                code_type: 'kd_changepass',
                mobile: mobile
            }).then(function (results) {
                if (results.error) {
                    res.send({code: 101, message: "验证码错误"});
                } else {
                    //验证通过,开始注册
                    assert.apiParseRequest('post', '/parse/functions/changeUserPassword', {
                        new_pass: password,
                        mobile: mobile
                    }).then(function (results) {
                        if (!results.error) {
                            //修改成功
                            res.send({code: 200, message: "修改成功"});
                        } else {
                            res.send({code: 400, message: "修改失败"});
                        }
                    }, function (err, error) {
                        res.send({code: 404, message: "网络错误"});
                    })
                }
            }, function (err, error) {
                res.send({code: 404, message: "请求验证失败"});
            })
        } else {
            res.send({code: 404, message: "非法的请求"});
        }
    })
};

exports.loginTransit = function (req,res,next) {
    res.render('login');
};

/**
 * 检查session中是否存在
 * @param req
 * @param res
 * @param next
 */
exports.sessionLogin = function (req,res,next) {
    var userId = assert.getUserId(req);
    if(userId){
        res.send(assert.getRes(200,"获取成功",{userId:userId}));
    }else{
        res.send(assert.getRes(102,"获取失败"));
    }
};
